﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebSocketClient.service;

namespace WebSocketClient
{
    // 定义修改输出的委托
    public delegate void ShowTextDelegate(int Index, string Addstr);
    public partial class WebSocketClientForm : Form
    {
        WebSocketService wss = null;
        WebSocketBase wb = null;
        // new Work 中再起的子线程调用的ShowTextDelegate委托事件，所以需要委托才能调用textBox控件
        public delegate void ChangeTextDelegate(int Index, string AddStr);
        //BuissnesServiceImpl buissnesServiceImpl = null;
        public WebSocketClientForm()
        {
            InitializeComponent();
            wss = new BuissnesServiceImpl();
            //buissnesServiceImpl = new BuissnesServiceImpl();
            wss.ShowTextEvent += new ShowTextDelegate(ChangeTextValue);

        }

        private void ChangeTextValue(int Index, string AddStr)
        {
            ListBox ChangeTextBox = null;
            switch (Index)
            {
                case 1:
                    ChangeTextBox = this.lstRes;
                    break;

            }

            if (ChangeTextBox.InvokeRequired)
            {
                ChangeTextDelegate pd = new ChangeTextDelegate(ChangeTextValue);
                ChangeTextBox.Invoke(pd, new object[] { Index, AddStr });
            }
            else
            {
                //ChangeTextBox.Items.Add(AddStr);
                //if (ChangeTextBox.Items.Count > 1000) ChangeTextBox.Items.Clear();
                string str = DateTime.Now.ToString("yy-MM-dd HH:mm:ss=>") + AddStr;
                ChangeTextBox.Items.Insert(0, str);
                tsslMsg.Text = str;
            }

        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string ip = txtIP.Text.Trim();
            string port = txtPort.Text.Trim();
            string url = "ws://"+ip+":"+port;

            //国际站配置为"wss://real.okcoin.com:10440/websocket/okcoinapi"

            wb = new WebSocketBase(url, wss);
            wb.start();

            //wb.send("{'event':'addChannel','channel':'ok_sub_spotcny_btc_ticker'}");

            //发生断开重连时，需要重新订阅
            //while (true) { 
            //    if(wb.isReconnect()){
            //        wb.send("{'event':'addChannel','channel':'ok_sub_spotcny_btc_ticker'}");
            //    }
            //    Thread.Sleep(1000);
            //}

            //Console.ReadKey();
           
        }

        private void WebSocketClientForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (wb != null)
            {
                wb.stop();  //优雅的关闭，程序退出时需要关闭WebSocket连接
                wb = null;
            }
        }

        private void btnSend1_Click(object sender, EventArgs e)
        {
            SendData(txtData1);
        }

        private void SendData(RichTextBox tb)
        {
            string data = tb.Text.Trim();
            if (wb != null)
            {
                wb.send(data);
            }
            else
            {
                MessageBox.Show("请先连接服务器~");
            }
        }

        class BuissnesServiceImpl : WebSocketService
        {
            /// <summary>
            ///
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static string DeCode(string str)
            {
                var regex = new Regex(@"\\u(\w{4})");

                string result = regex.Replace(str, delegate (Match m)
                {
                    string hexStr = m.Groups[1].Value;
                    string charStr = ((char)int.Parse(hexStr, System.Globalization.NumberStyles.HexNumber)).ToString();
                    return charStr;
                });

                return result;
            }

            public event ShowTextDelegate ShowTextEvent;
            public void onReceive(string msg)
            {

                string str = DeCode(msg);
                Console.WriteLine(str);
                ShowTextEvent.Invoke(1, str);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            SendData(txtData2);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            SendData(richTextBox4);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            SendData(richTextBox5);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            SendData(richTextBox6);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            SendData(richTextBox1);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SendData(richTextBox7);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            SendData(richTextBox2);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lstRes_SelectedIndexChanged(object sender, EventArgs e)
        {
            tsslMsg.Text = lstRes.SelectedItem.ToString();
        }
    }


}
